package race;

import java.util.PriorityQueue;

public class SimpleDivideCompute implements ComputeRunnable {

	SimpleShareData ssd;
	int size;
	int offset;
	public SimpleDivideCompute(SimpleShareData ssd, int size, int offset) {
		this.ssd = ssd;
		this.size = size;
		this.offset = offset;
	}
	
	@Override
	public void run() {
		go();

	}

	@Override
	public void go() {
		System.out.println("开始计算随机数: " + size + " " + offset);
		int[] alist = new int[size];
		for (int i = 0; i < size; i++) {
			// alist[i] = ssd.getScore().indexOf(offset * size + i);
			alist[i] = ssd.getScore().get(offset * size + i);
		}
		// Arrays.sort(alist);
		alist = getMaximumNumbers(alist,10);

		for (int i = 0; i < 10; i++) {
			//System.out.println("随机数: " + alist[i]);
			ssd.addExchange(alist[alist.length - i - 1]);
		}
		ssd.getCompSig().countDown();;
		//System.out.println("计算随机数完毕: " + size + " " + SimpleShareData.BUFSIZE * size / SimpleShareData.COUNT);
	}

	public int[] getMaximumNumbers(int[] arr, int k) {
		int[] vec = new int[k];
		if (k == 0) { // 排除 0 的情况
			return vec;
		}
		PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
		for (int i = 0; i < k; ++i) {
			queue.offer(arr[i]);
		}
		for (int i = k; i < arr.length; ++i) {
			if (queue.peek() < arr[i]) {
				queue.poll();
				queue.offer(arr[i]);
			}
		}
		for (int i = 0; i < k; ++i) {
			vec[i] = queue.poll();
		}
		return vec;
	}
}
